const cards=document.querySelectorAll('.card');
const btns=document.querySelectorAll('.js-btn');

btns.forEach(btn=>{
    btn.addEventListener('click',on_btn_click,true);
    btn.addEventListener('touch',on_btn_click,true);
});

function on_btn_click(e){
    const nextID=e.currentTarget.getAttribute('data-target');
    const next=document.getElementById(nextID);
    if(!next)return;
    //修改类名，用 css 根据类名调整背景和显示
    bg_change(nextID);
    view_change(next);
    return false;
}

function bg_change(next){
    document.body.className='';
    document.body.classList.add('is-'+next);
}

function view_change(next){
    cards.forEach(card=>{
        card.classList.remove('is-show');
    });
    next.classList.add('is-show');
}

// 注册表单提交事件
document.getElementById("registerForm").addEventListener("submit", async (e) => {
    e.preventDefault();

    // 构造请求参数
    const formData = new URLSearchParams({
        userName: e.target.userName.value,
        password: e.target.password.value,
        email: e.target.email.value
    });

    try {
        const response = await fetch("/CloudDriver_war/register", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: formData
        });

        const data = await response.json();

        if (data.status === "success") {
            // 注册成功时自动登录
            alert("注册成功，已自动登录");
            sessionStorage.setItem("token", data.token);
            window.location.href = "/CloudDriver_war/";
        } else {
            // 注册失败时显示具体原因
            alert(`注册失败: ${data.message}`);
            // 清空密码字段
            e.target.password.value = "";
        }
    } catch (error) {
        console.error("注册请求失败:", error);
        alert("网络错误，请检查连接后重试");
    }
})

// 登录表单提交事件
document.getElementById("loginForm").addEventListener("submit", async(e) => {
    e.preventDefault(); // 阻止表单默认提交行为

    fetch("/CloudDriver_war/login", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: new URLSearchParams({
            email: e.target.email.value,
            password: e.target.password.value
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data["status"] === "success") {
                // 登录成功
                alert("登录成功");
                // 将 token 存储在 sessionStorage 中
                sessionStorage.setItem("token", data["token"]);
                window.location.href = "/CloudDriver_war/";
            }
            else {
                // 登录失败，提示错误信息，跳转到登录页面
                alert("登录失败: " + data["message"]);
                window.location.href = "/CloudDriver_war/";
            }
        })
        .catch(error => {
            console.error("Error:", error);
        })
})

// 进入网盘按钮点击事件
document.getElementById("enter-button").addEventListener("click", async(e) => {
    e.preventDefault(); // 阻止表单默认提交行为

    if (sessionStorage.getItem('token') == null) {
        alert("请先登录");
    }
    else {
        fetch("/CloudDriver_war/filelist", {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: new URLSearchParams({
                token: sessionStorage.getItem('token')
            })
        })
            .then(response => response.text())
            .then(html => {
                document.open();
                document.write(html);
                document.close();
            })
            .catch(error => {
                console.error("Error:", error);
            })
    }
})